//
// Created by lymk on 2021/8/8.
//

#include "AnimeComponent.h"
#include "../GMath.h"
#include "../Actor/GameActor.h"
#include "string"

void AnimeComponent::update(double DeltaSeconds, RenderUtils renderUtils,GameActor* actor) {

    switch (animeState) {
        case IDLE:{
            nowFrame = 0;
        }break;
        case WALK:{
            animeCool->Update(DeltaSeconds);
            if(animeCool->GetFlag()){
                nowFrame = (nowFrame + 1) % MAX_FRAME_NUM;
                animeCool->ReSet();
            }
        }break;
        case JUMP:{
            nowFrame = 1;
        }
    }

    play_move(DeltaSeconds,renderUtils,actor);
}

void AnimeComponent::play_move(double DeltaSeconds, RenderUtils renderUtils,GameActor *actor) {
    GMath::Vec2 pos = actor->getRenderPos();
    GMath::Vec2 spd = actor->getActorSpeed();
    if(spd.X>0)face = 1;
    if(spd.X<0)face = 2;
    BITMAPINFO bmInfo;
    memset(&bmInfo.bmiHeader, 0, sizeof(BITMAPINFOHEADER));
    bmInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmInfo.bmiHeader.biWidth = animeData->width;
    bmInfo.bmiHeader.biHeight = -1*animeData->height;
    bmInfo.bmiHeader.biPlanes = 1;
    bmInfo.bmiHeader.biBitCount = animeData->nrChannels * 8;//32位位图支持透明度
    int tmpx = nowFrame * animeData->width/4,tmpy = animeData->height/4 * face;
    //int tmpx = 0,tmpy = 0;
    SetDIBitsToDevice(renderUtils.tmpDC, pos.X, pos.Y, animeData->width/4, animeData->height/4, tmpx, tmpy, 0, animeData->height, animeData->data, &bmInfo, 0);
    //BitBlt(PDC,0,0,width,height,tmpDC,0,0,SRCPAINT);
    BLENDFUNCTION bf = {0};
    bf.BlendOp = AC_SRC_OVER;
    bf.BlendFlags = 0;
    bf.AlphaFormat = 1;
    bf.SourceConstantAlpha = 255;
    AlphaBlend(renderUtils.bufDC,0,0,renderUtils.dcWidth,renderUtils.dcHeight,renderUtils.tmpDC,0,0,renderUtils.dcWidth,renderUtils.dcHeight,bf);
}

AnimeState AnimeComponent::getAnimeState() const {
    return animeState;
}

void AnimeComponent::setAnimeState(AnimeState animeState) {
    AnimeComponent::animeState = animeState;
}

void AnimeComponent::Initialize(std::string path, float interval, int frameNum) {
    PicData tmp = LoadPNG(path);
    if(tmp.data!= nullptr){
        animeData = new PicData;
        *(animeData) = tmp;
    }
    animeCool = new CoolUtil(interval);
    MAX_FRAME_NUM = frameNum;
    nowFrame = 0;
    face = 1;
}

void AnimeComponent::Finalize() {
    delete animeData;
    delete animeCool;
}

PicData *AnimeComponent::getAnimeData() const {
    return animeData;
}

void AnimeComponent::setAnimeData(PicData *animeData) {
    AnimeComponent::animeData = animeData;
}

